<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 *
 * @package		anime
 * @author		Tran Hoang Thien (thienhb12@gmail.com)
 * @copyright   PHP TEAM
 * @link		http://phpandmysql.net
 * @since		Version 1.0
 * @phone       0944418192
 *
 */
	class Episode extends My_Controller{
		
		public function __construct(){
			parent:: __construct();
			$this->load->model('episode_model');
			$this->load->model('film_model');
			$this->load->model('mserver');
			$this->load->library('form_validation');
			$this->load->helper('url');
			if(!$this->session->userdata("session_user") || $this->session->userdata("session_level") != 1){
				redirect(base_url()."admin/login");
			}
		}

		public function index(){
			$id_film                   = $this->uri->segment(4);
			$data['title']             = 'Danh sách tập phim';
			$data['color']             = '#33925c';
			$data['template']          = 'episode/list_episode';
			$config['base_url']        = base_url('admin/episode/index').'/'.$id_film;
			$config['total_rows']      = $this->episode_model->count_all();
			$config['per_page']        = 20;
			$config['uri_segment']     = '5';
			$config['first_link']      = '<<';
			$config['last_link']       = '>>';
			$config['first_tag_open']  = '<li class="click">';
			$config['first_tag_close'] = '</li>';
			$config['last_tag_open']   = '<li class="click">';
			$config['last_tag_close']  = '</li>';
			$config['prev_tag_open']   = '<li class="click">';
			$config['prev_tag_close']  = '</li>';
			$config['next_tag_open']   = '<li class="click">';
			$config['next_tag_close']  = '</li>';
			$config['num_tag_open']    = '<li class="click">';
			$config['num_tag_close']   = '</li>';
			$config['next_link']       = 'Next';
			$config['prev_link']       = 'Prev';
			$config['cur_tag_open']    = '<li class="active"><a>';
			$config['cur_tag_close']   = '</a></li>';
			$this->load->library("pagination");
			$this->pagination->initialize($config);
			$start                     = $this->uri->segment(5)?$this->uri->segment(5):0;
			$param                     = array();
			$param['select']           = array('epid','idphim','url','epname','sub','server');
			$param['where']			   = array('idphim'=>$id_film);
			$param['limit']            = array($config['per_page'] ,$start);
			$param_server              = array();
			$param_server['select']    = array('idserver','nameserver');
			$result_server             = $this->mserver->get_list($param_server);
			$data['server']            = array();
			if(!empty($result_server)){
				foreach($result_server as $value){
					$data['server'][$value['idserver']] = $value['nameserver']; 
				}
			}
			$data['result']            = $this->episode_model->get_list($param);
			$data['id_film']           = $id_film;
			$this->load->view("layout",$data);
		}

		public function add(){
			$data['title']         = 'Thêm mới tập phim';
			$data['color']         = '#33925c';
			$data['template']      = 'episode/add_episode_film';
			$id_film               = $this->uri->segment(4);
			$data['id_film']       = $id_film;   
			$param_film            = array('name');
			$data['film_name']     = $this->film_model->get_info($id_film,$param_film);
			$param_server          = array('idserver','nameserver');
			$data['result_server'] = $this->mserver->get_list($param_server);
			$check_request         = $this->input->post();
			if(!empty($check_request)){
				$this->form_validation->set_rules('epname','epname', 'required|trim|xss_clean');
				$this->form_validation->set_rules('url','url','required|trim|xss_clean');
				if($this->form_validation->run() == FALSE){
					$data['title']    = 'Thêm mới tập phim';
					$data['color']    = '#33925c';
					$data['template'] = 'episode/add_episode_film';
					$this->load->view('layout',$data);
				}else{
					$epname      = fillter($this->input->post('epname'));
					$url         = fillter($this->input->post('url'));
					$server      = $this->input->post('server');
					$db = array(
						'epname' => $epname,
						'url'    => $url,
						'idphim' => $id_film,
						'server' => $server
					);

					$new_ep      = $this->input->post('new_ep');
					
					if(empty($new_ep)){
						$new_id_ep  = $this->episode_model->save($id = false,$db);
						$rewrite	= str_replace(' ', '-',strtolower(str_replace('%','n',replace($data['film_name']['name'])))).'-ep-'.$epname.'-'.$new_id_ep;
						$db_film    = array(
							'timepost'  => time(),
							'urlep_new' => $rewrite
						);
						$this->film_model->save($id_film,$db_film);
					}else{
						$this->episode_model->save($new_ep,$db);
					}
					$path              = 'upload/sub/';
					$path             .=  date('Y');

					if($_FILES["file"]["name"] != NULL){
						if(!is_dir($path)){
							mkdir($path,0777);
						}
						$config['upload_path']   = $path;
						$config['file_name']     = !empty($new_id_ep)?$new_id_ep:$new_ep;
						$config['allowed_types'] = 'srt|ass';
						$config['max_size']      = '10000';
						$this->load->library('upload',$config);
						$this->upload->initialize($config);
						if(!$this->upload->do_upload("file")){
							$data                  = array('error' => $this->upload->display_errors());
							$data['title']         = 'Thêm mới thể loại';
							$data['color']         = '#33925c';
							$data['template']      = 'episode/add_episode_film';
							$id_film               = $this->uri->segment(4);
							$data['id_film']       = $id_film;
							$param_film            = array('name');
							$data['film_name']     = $this->film_model->get_info($id_film,$param_film);
							$param_server          = array('idserver','nameserver');
							$data['result_server'] = $this->mserver->get_list($param_server); 
							$data['new_id_ep']     = $new_id_ep;   
							$this->load->view('layout',$data);
							return FALSE;
						}else{
							$file = $this->upload->data();
							$info = array(
								'sub' => $config['upload_path'].'/'.$file['file_name']
							);
							$this->episode_model->save($config['file_name'],$info);
						}
					}
					redirect(base_url("admin/film"));
				}
			}else{
				$this->load->view('layout',$data);
			} 
		}

		public function edit(){
			$data['title']         = "Sửa thông tin tập phim";
			$data['color']         = "#33925c";
			$data['template']      = 'episode/edit_episode';
			$id                    = $this->uri->segment(4);
			$id_film               = $this->uri->segment(5);
			$data['id_film']       = $id_film;   
			$param_film            = array('name');
			$data['film_name']     = $this->film_model->get_info($id_film,$param_film);
			$param_server          = array('idserver','nameserver');
			$data['result_server'] = $this->mserver->get_list($param_server);
			if(isset($id)){
				if(!empty($this->input->post())){
					$this->form_validation->set_rules('epname','epname', 'required|trim|xss_clean');
					$this->form_validation->set_rules('url','url','required|trim|xss_clean');
					if($this->form_validation->run() == FALSE){
						$data['title']         = 'Thêm mới tập phim';
						$data['color']         = '#33925c';
						$data['template']      = 'episode/edit_episode';
						$this->load->view('layout',$data);
					}else{
						
						$epname      = fillter($this->input->post('epname'));
						$url         = fillter($this->input->post('url'));
						$server      = $this->input->post('server');
						$db = array(
							'epname' => $epname,
							'url'    => $url,
							'idphim' => $id_film,
							'server' => $server
						);
						$this->episode_model->save($id,$db);
						$path              = 'upload/sub/';
						$path             .=  date('Y');

						if($_FILES["file"]["name"] != NULL){
							if(!is_dir($path)){
								mkdir($path,0777);
							}
							$config['upload_path']   = $path;
							$config['file_name']     = $id;
							$config['allowed_types'] = 'srt|ass';
							$config['max_size']      = '10000';
							$this->load->library('upload',$config);
							$this->upload->initialize($config);
							if(!$this->upload->do_upload("file")){
								$data                  = array('error' => $this->upload->display_errors());
								$data['title']         = 'Thêm mới thể loại';
								$data['color']         = '#33925c';
								$data['template']      = 'episode/edit_episode';
								$param_film            = array('name');
								$param                 = array('idphim','epname','url','sub','server','epid');
								$param_server          = array('idserver','nameserver');
								$data['id_film']       = $id_film;
								$id                    = $this->uri->segment(4);
								$data['result']        = $this->episode_model->get_info($id,$param);
								$data['film_name']     = $this->film_model->get_info($id_film,$param_film);
								$data['result_server'] = $this->mserver->get_list($param_server);
								$this->load->view('layout',$data);
								return FALSE;
							}else{
								$old_sub = $this->input->post('sub');
								@unlink($old_sub);
								$file = $this->upload->data();
								$info = array(
									'sub' => $config['upload_path'].'/'.$file['file_name']
								);
								$this->episode_model->save($config['file_name'],$info);
							}
						}
						redirect(base_url("admin/episode/index/".$id_film.""));
					}
				}else{
					if(!empty($id)){
						$param          = array('idphim','epname','url','sub','server','epid');
						$data['result'] = $this->episode_model->get_info($id,$param);
						$this->load->view('layout',$data);
					}
				}
			}else{
				redirect(base_url("admin/episode/index/".$id_film.""));
			}
		}

		public function multi(){
			$data['title']          = "Thêm nhiều tập phim";
			$data['color']          = "#33925c";
			$data['template']       = 'episode/multi_episode';
			$id_film                = $this->uri->segment(4);
			$data['id_film']	    = $id_film;
			$data['film_name']      = $this->film_model->get_info($id_film,array('name'));	
			$param_server           = array();
			$param_server['select'] = array('idserver','nameserver');
			$data['result_server']  = $this->mserver->get_list($param_server);
			$request   				= $this->input->post();
			if(!empty($request)){
				$this->form_validation->set_rules('multi','multi','required|trim|xss_clean');
				if($this->form_validation->run() == FALSE){
					$data['title']          = "Thêm nhiều tập phim";
					$data['color']          = "#33925c";
					$data['template']       = 'episode/multi_episode';
					$id_film                = $this->uri->segment(4);
					$data['film_name']      = $this->film_model->get_info($id_film,array('name'));		
					$param_server           = array();
					$param_server['select'] = array('idserver','nameserver');
					$data['result_server']  = $this->mserver->get_list($param_server);
					$this->load->view('layout',$data);
				}else{
					$data['title']        = "Thêm nhiều tập phim";
					$data['color']        = "#33925c";
					$data['film_id']	  = $id_film;
					$multi                = $this->input->post('multi');
					$data['name']         = $this->input->post('name');
					$data['arr_multi']    = explode('<br />',nl2br(trim($multi)));
					$data['number_multi'] = count($data['arr_multi']);
					$data['template']     = 'episode/add_episode';
					$data['server']       = $this->input->post('server');
					$this->load->view('layout',$data);
				}
			}else{
				$this->load->view('layout',$data);
			}
		}

		public function multi_ep(){
			$request = $this->input->post();
			if(!empty($request)){
				$data    = array();
				$db      = array();
				$id_film = $this->uri->segment(4);
				$name_ep = $this->input->post('epname');
				$url     = $this->input->post('url');
				$name    = $this->input->post('name');
				if(!empty($name_ep)){
					foreach($name_ep as $key => $value){
						$db[$key]['epname'] = $value;
						$db[$key]['idphim'] = $id_film;
					}
				}

				if(!empty($url)){
					foreach($url as $key => $value){
						$db[$key]['url']    = $value;
						$db[$key]['server'] = $this->input->post('server');        
					}
				}

				foreach($db as $value){
					$data[] = $value;
				}
				
				foreach($data as $value){
					$new_ep_id = $this->episode_model->save($id = false,$value);
				}
				$rewrite	= str_replace(' ', '-',strtolower(str_replace('%','n',replace($name)))).'-ep-'.$new_ep_id;
				$film_data  = array(
					'timepost'  => time(),
					'urlep_new' => $rewrite
				);
				$this->film_model->save($id_film,$film_data);

				redirect(base_url("admin/episode/index/".$id_film.""));
			}
		}

		public function delete(){
			$id   = $this->uri->segment(4);
			$f_id = $this->uri->segment(5);
			if(!empty($id)){
				$param           = array('sub');
				$result          = $this->episode_model->get_info($id,$param);
				@unlink($result['sub']);
				$this->episode_model->delete($id);
				redirect(base_url("admin/episode/index/".$f_id.""));
			}
		}

		public function bulk_action(){
			$var      = array();
			$request  = $this->input->post();
			if(!empty($request)){
				$type = $this->uri->segment(4);
				$uid  = $this->input->post('id');
				$id   = $this->session->userdata('session_user_id'); 
				if($type == 'delete'){
					if(!empty($uid)){
						foreach($uid as $value){
							$param = array('iduser' => $value,'iduser !=' => $id);
							$this->muser->delete_rule($param);
						}
					}
					$var['action'] = 'delete';
				}elseif($type == 'publish'){
					if(!empty($uid)){
						foreach($uid as $value){
							$where = array('iduser'=> $value,'iduser !=' => $id);
							$data  = array('user_activation' => 1) ;
							$this->muser->update_rule($where,$data);
						}
					}
					$var['action'] = 'publish';
				}elseif($type == 'unpublish'){
					if(!empty($uid)){
						foreach($uid as $value){
							$where = array('iduser'=> $value,'iduser !=' => $id);
							$data  = array('user_activation' => 2) ;
							$this->muser->update_rule($where,$data);
						}
					}
					$var['action'] = 'unpublish';
				}
				$var['error'] = 0;
			}else{
				$var['error'] = 1;
			}
			$var['url'] = base_url('admin/users/list_all');
			exit(json_encode($var));
		}
	}